<template>
  <el-dialog 
    title="确认打款" 
    v-model="dialogVisible" 
    width="1200" 
    append-to-body
    @close="handleClose"
  >
    <div v-loading="loading">
      <!-- 提现信息 -->
      <el-descriptions title="提现信息" :column="2" border class="mb20">
        <el-descriptions-item label="申请编号">{{ withdrawInfo.withdrawId }}</el-descriptions-item>
        <el-descriptions-item label="申请标题">{{ withdrawInfo.title }}</el-descriptions-item>
        <el-descriptions-item label="公寓名称">{{ withdrawInfo.apartmentName }}</el-descriptions-item>
        <el-descriptions-item label="提现金额">
          <span class="amount-text">¥{{ withdrawInfo.amount }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="收款账户">{{ withdrawInfo.paymentAccountName }}</el-descriptions-item>
        <el-descriptions-item label="银行账号">{{ formatBankCard(withdrawInfo.bankAccount) }}</el-descriptions-item>
        <el-descriptions-item label="开户行">{{ withdrawInfo.bankName }}</el-descriptions-item>
        <el-descriptions-item label="持卡人">{{ withdrawInfo.accountHolder }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ parseTime(withdrawInfo.applyTime) }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ parseTime(withdrawInfo.auditTime) }}</el-descriptions-item>
      </el-descriptions>

      <!-- 关联账单信息 -->
      <associate-bills-table 
        :withdraw-id="withdrawInfo.withdrawId" 
        v-if="withdrawInfo.withdrawId"
      />

      <!-- 打款凭证上传表单 -->
      <el-form ref="paymentFormRef" :model="paymentForm" :rules="paymentRules" label-width="120px" class="mt20">
        <el-form-item label="打款凭证" prop="paymentVoucher" required>
          <el-upload
            ref="uploadRef"
            :action="uploadAction"
            :headers="uploadHeaders"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            accept="image/*,.pdf"
            list-type="picture-card"
            :limit="1"
          >
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png/pdf格式，文件大小不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="paymentForm.remark" 
            type="textarea" 
            placeholder="请输入打款备注信息"
            :rows="3"
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="confirmLoading">确认打款</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, getCurrentInstance } from 'vue'
import { getWithdraw, confirmPayment } from "@/api/apartment/withdraw"
import { getToken } from "@/utils/auth"
import { Plus } from '@element-plus/icons-vue'
import AssociateBillsTable from "./AssociateBillsTable.vue"

const { proxy } = getCurrentInstance()

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  withdrawId: {
    type: [String, Number],
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const dialogVisible = ref(false)
const loading = ref(false)
const confirmLoading = ref(false)
const withdrawInfo = ref({})
const fileList = ref([])

const paymentForm = reactive({
  paymentVoucher: '',
  remark: ''
})

const paymentRules = {
  paymentVoucher: [
    { required: true, message: '请上传打款凭证', trigger: 'change' }
  ]
}

// 上传配置
const uploadAction = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload")
const uploadHeaders = ref({ Authorization: "Bearer " + getToken() })

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val && props.withdrawId) {
    loadData()
  }
})

watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 获取提现详情
    const withdrawRes = await getWithdraw(props.withdrawId)
    withdrawInfo.value = withdrawRes.data
  } catch (error) {
    proxy.$modal.msgError('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 上传成功回调
const handleUploadSuccess = (response, file) => {
  if (response.code === 200) {
    paymentForm.paymentVoucher = response.data.url
    proxy.$modal.msgSuccess('上传成功')
  } else {
    proxy.$modal.msgError(response.msg || '上传失败')
    fileList.value = []
  }
}

// 上传失败回调
const handleUploadError = () => {
  proxy.$modal.msgError('上传失败，请重试')
  fileList.value = []
}

// 移除文件回调
const handleRemove = () => {
  paymentForm.paymentVoucher = ''
}

// 上传前校验
const beforeUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    proxy.$modal.msgError('上传文件只能是 JPG/PNG/PDF 格式!')
    return false
  }
  if (!isLt10M) {
    proxy.$modal.msgError('上传文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 确认打款
const handleConfirm = async () => {
  console.log(paymentForm.paymentVoucher)
  try {
    await proxy.$refs.paymentFormRef.validate()
    
    confirmLoading.value = true
    
    const data = {
      paymentVoucher: paymentForm.paymentVoucher,
      remark: paymentForm.remark
    }
    
    await confirmPayment(props.withdrawId, data)
    
    proxy.$modal.msgSuccess('打款确认成功')
    emit('success')
    handleClose()
  } catch (error) {
    if (error !== 'cancel') {
      proxy.$modal.msgError('打款确认失败')
    }
  } finally {
    confirmLoading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  // 重置表单
  paymentForm.paymentVoucher = ''
  paymentForm.remark = ''
  fileList.value = []
  if (proxy.$refs.paymentFormRef) {
    proxy.$refs.paymentFormRef.resetFields()
  }
}

// 格式化银行卡号
const formatBankCard = (cardNumber) => {
  if (!cardNumber) return ''
  return cardNumber.replace(/(\d{4})(?=\d)/g, '$1 ')
}
</script>

<style scoped>
.amount-text {
  color: #f56c6c;
  font-weight: bold;
}

.mb20 {
  margin-bottom: 20px;
}

.mt20 {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style> 